import calendar from '../view/calendar/index'
import '../style/style.scss'

import $ from 'jquery'

;(function( $ ){
    
    const root = document.getElementById('root'),
            CaNd = calendar();

    let year = '',
        month = '',
        day = '',
        today = '',
        showTitle = '',
        activeDate = '',
        startDate = '',
        startTime = 0,
        endTime = 0,
        isStart = true,
        min = null,
        max = null,
        days = 0,
        minYear = 1950,
        maxYear = 2050,
        weekday = 0,
        weekdayArr = [],
        daysArr = [],
        mode = 'date',
        _obj = {};

    function init( options ) {
        let now = new Date();
        year = now.getFullYear();
        month = now.getMonth() + 1;
        day = now.getDate();
        today = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
        activeDate = today;
        min = initData( options && options.minDate || '' );
        max = initData( options && options.maxDate || today );
        ChangeData();
        render();
        bindEvent();
    }

    function ChangeData() {

        // 获取一个月有多少天
        days = getMonthDay( year, month );
        // 创建当前这个月的日期天数
        daysArr = generateArray( 1, days );
        weekday = getweekday( year, month );
        console.log( '千锤百炼', weekday );
        weekdayArr = generateArray( 1, weekday );
        showTitle = `${year}年${month}月`
        _obj = {
            year,
            month,
            day,
            daysArr,
            weekday,
            showTitle,
            mode
        }
    }
    
    function getMonthDay( year, month ) {
        return new Date( year, month, 0 ).getDate();
    }

    function generateArray( start, end ) {
        return Array.from(new Array(end + 1).keys()).slice(start)
    }

    function getweekday( year, month ) {
        let date = new Date(`${year}/${month}/01 00:00:00`);
        return date.getDay();
    }   

    function initData( date ) {
        let stx = date.split('-');
        return {
            year: Number(stx[0] || 1920),
            month: Number(stx[1] || 1),
            day: Number(stx[2] || 1)
        }
    }

    function render() {
        root.innerHTML = CaNd.tpl( _obj );
    }

    function bindEvent() {
        CaNd.bindEvent( { typeClick });
    }

    function typeClick( type, { day }, callback ) {
        if ( type === 'section' ) {
            openDisAbled( day, callback );
        } else if ( type === 'changeMonthHandler' ) {
            changeMonthHandler( day, callback );
        } else if ( type === 'changYearHandler' ) {
            changYearHandler( day, callback );
        } else if ( type === 'ChangeDouble' ) {
            ChangeDouble( callback, day );
        } else if ( type === 'submit' ) {
            submit();
        } else if ( type === 'alone' ) {
            alone( day );
        }
    }

    function openDisAbled( day, callback ) {
        let bool = true;
        if ( day == '' ) return bool;
        
        let date = `${year}/${month}/${day}`;
        let minTime = `${min.year}/${min.month}/${min.day}`;
        let maxTime = `${max.year}/${max.month}/${max.day}`;
        let timestamp = new Date(date).getTime();
        // 如果点击的日期再此月内就执行
        if ( timestamp >= new Date(minTime).getTime() && timestamp <= new Date(maxTime).getTime() ) {
            bool = false;
        }
        callback( bool, _obj );
    }

    // 切换月份
    function changeMonthHandler( isAdd, callback ) {
        if ( isAdd === '1' ) {
            month += 1;
            let Year = month > 12 ? year + 1 : year;
            if ( !checkRange( Year ) ) {
                month = month > 12 ? 1 : month;
                year = Year;
                _obj.month = month;
                _obj.year = Year;
                ChangeData();
                callback(_obj);
            }

        } else {
            month -= 1;
            let Year = month < 1 ? year - 1 : year;
            if ( !checkRange( Year ) ) {
                month = month < 1 ? 12 : month;
                year = Year;
                _obj.month = month;
                _obj.year = Year;
                ChangeData();
                callback(_obj);
            }
        }
    }
    // 切换年份
    function changYearHandler( isAdd, callback ) {
        year = isAdd === '1' ? year + 1 : year - 1;
        if ( !checkRange( year ) ) {
            ChangeData();
            _obj.year = year;
            callback( _obj );
        }
    }

    function ChangeDouble( callback, day ) {
        let date = `${year}-${month}-${day}`;
        let compare = new Date(date.replace(/\-/g, '/')).getTime() < new Date( startDate.replace(/\-/g,'/') ).getTime()
        if ( isStart || compare ) {
            startDate = date;
            isStart = false;
            callback( 'start' );
            startTime = `${year}-${month}-${day}`;
        } else {
            isStart = true;
            callback( 'end' );
            endTime = `${year}-${month}-${day}`;
        }
    }

    function checkRange( year ) {
        let overstep = false;
        if ( year < minYear || year > maxYear ) {
            overstep = true;
        }
        return overstep;
    }

    function alone( day ) {
        startTime = `${year}-${month}-${day}`;
    }

    function submit() {
        if ( mode === 'date' ) {
            $('.text').text( startTime );
        } else {
            $('.text').text( `${startTime} 至 ${endTime}` );
        }
        CaNd.CloseCalendar();
    }

    init();

})( $ )